import { setToken, getToken } from '../../utils/token'

import { getUserInfo } from '../../api/getUserInfo'
import { loginWeb } from '../../api/login'

const state = {
  token: getToken(),
  authorityList: [],
  username: '',
  roleId: '',
  userId: ''
}

const mutations = {
  // 设置token
  set_token (state, token) {
    state.token = token
  },
  // 设置当前用户名称
  set_username (state, username) {
    state.username = username
  },
  // 设置当前用户角色ID
  set_roleId (state, roleId) {
    state.roleId = roleId
  },
  // 设置当前用户userId
  set_userId (state, userId) {
    state.userId = userId
  },
  // 设置当前角色的权限表
  set_authorityList (state, authorityList) {
    state.authorityList = authorityList
  }
}

const actions = {
  // 用户登录
  userLogin ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginWeb(username.trim(), password).then(res => {
        if (res.data.code === '200') {
          commit('set_token', res.data.token)
          setToken(res.data.token)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 获取用户信息
  getUserInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        if (res.data.code === (200 || '200')) {
          commit('set_username', res.data.data.username)
          commit('set_roleId', res.data.data.roleId)
          commit('set_userId', res.data.data.userId)
          commit('set_authorityList', res.data.data.authorityList)
        }

        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
